//
//  SectionsViewController.m
//  Sections
//
//  Created by Dave Mark on 12/8/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SectionsViewController.h"
#import "NSDictionary-MutableDeepCopy.h"
//#import "DDList.h"
#import "PassValueDelegate.h"
#import "Top10.h"
#import "BoardDetail.h"
#import "RegexKitLite.h"

@implementation SectionsViewController
@synthesize names;
@synthesize keys;
@synthesize table;
@synthesize search;
@synthesize allNames;
@synthesize nameSection;


#pragma mark -
#pragma mark Custom Methods
- (void)resetSearch {
    NSMutableDictionary *allNamesCopy = [self.allNames mutableDeepCopy];
    self.names = allNamesCopy;
    [allNamesCopy release];
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[self.allNames allKeys]
        sortedArrayUsingSelector:@selector(compare:)]];
    self.keys = keyArray;
    [keyArray release];
}

- (void)handleSearchForTerm:(NSString *)searchTerm {
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
	
    for (NSString *key in self.keys) {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
        for (NSString *name in array) {
            if ([name rangeOfString:searchTerm
							options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:name];
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:key];
		
        [array removeObjectsInArray:toRemove];
        [toRemove release];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [sectionsToRemove release];
    [table reloadData];
}

/*- (void)setDDListHidden:(BOOL)hidden {
	NSInteger height = hidden ? 0 : 120;
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:.2];
	//[_ddList.view setFrame:CGRectMake(30, 36, 200, height)];
	[UIView commitAnimations];
}*/

#pragma mark PassValue protocol
//这里还要再研究。。。DDList如何调用searchBarSearchButtonClicked
//现在的问题是如何把DDList的内容添加到search.Text里面
//上面的问题已经解决，现在只需要在DDList里面实现联想功能即可
/*- (void)passValue:(NSString *)value{
	if (value) {
        
        search.text = value;
        [self searchBarSearchButtonClicked:search];
        [search resignFirstResponder];
	}
	else {
		
	}
}*/


- (void)viewDidLoad {
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    self.navigationItem.title= @"板块搜索";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"boards"
                                                     ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc]
                          initWithContentsOfFile:path];
    self.allNames = dict;
    [dict release];
    
    search.barStyle = UIBarStyleBlackOpaque;
    
    /*_ddList = [[DDList alloc] initWithStyle:UITableViewStylePlain];
	_ddList._delegate = self;
	[self.view addSubview:_ddList.view];
	[_ddList.view setFrame:CGRectMake(30, 36, 200, 0)];*/

	
    [self resetSearch];
    [table reloadData];
    [table setContentOffset:CGPointMake(0.0,0) animated:NO];	
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    self.table = nil;
    self.search = nil;
    self.allNames = nil;
    self.names = nil;	
    self.keys = nil;
    [super viewDidUnload];
}

- (void)dealloc {
    [table release];
    [search release];
    [allNames release];
    [names release];	
    [keys release];
    [super dealloc];	
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return ([keys count] > 0) ? [keys count] : 1;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
	if ([keys count] == 0)
        return 0;
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
	searchBar.showsCancelButton = YES;
	for(id cc in [searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
	return YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
	
    NSString *key = [keys objectAtIndex:section];
    nameSection = [names objectForKey:key];
	
    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
							 SectionsTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
				 initWithStyle:UITableViewCellStyleDefault
				 reuseIdentifier:SectionsTableIdentifier] autorelease];
    }
	
    cell.textLabel.text = [nameSection objectAtIndex:row];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
	if ([keys count] == 0)
        return nil;

    NSString *key = [keys objectAtIndex:section];
	if (key == UITableViewIndexSearch)
        return nil;
    return key;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (isSearching)
        return nil;
    return keys;	
}

#pragma mark -
#pragma mark Table View Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [search resignFirstResponder];
    isSearching = NO;
    search.text = @"";
    [tableView reloadData];
    return indexPath;	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    
    BoardDetail *detailViewController = [[BoardDetail alloc] initWithNibName:@"Top10" bundle:nil];
    detailViewController.titlestring = [NSString stringWithFormat:[[nameSection objectAtIndex:indexPath.row] stringByMatching:@"^[\\w\\W]*(?=\\()"]];
    // ...
    
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
 
    //NSUInteger row = [indexPath row];
    //NSString *titlename = [nameSection objectAtIndex:row];
    //Top10 *forumViewController = [[Top10 alloc] init];
    
    /*NSString* i = @"http://bbs.nju.edu.cn/";
    NSString* href = [i stringByAppendingString:[[self.detail objectAtIndex:4]objectAtIndex:indexPath.row]];
    detailViewController.urlString = [NSString stringWithString:href];
    NSURL* url = [[NSURL alloc] initWithString:href];
    NSData* data = [[NSData alloc] initWithContentsOfURL:url];
    [detailViewController getDetail:data];
    detailViewController.titlestring = [[self.detail objectAtIndex:0] objectAtIndex:indexPath.row];*/
    // ...
    // Pass the selected object to the new view controller.
    //[self.navigationController pushViewController:forumViewController animated:YES];
    //[forumViewController release];
    
    //[self resetSearch];
    //[table reloadData];
    
}


#pragma mark -
#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [search resignFirstResponder];
    NSString *searchTerm = [searchBar text];
    //[self setDDListHidden:YES];
        [self handleSearchForTerm:searchTerm];
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchTerm {
    search.showsCancelButton= YES;
    if ([searchTerm length] == 0) {
        [self resetSearch];
        [table reloadData];
        //[self setDDListHidden:YES];
        return;
    }
    else{
        //_ddList._searchText = searchTerm;
		//[_ddList updateData];
        //[self setDDListHidden:YES];
    }
    [self handleSearchForTerm:searchTerm];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    isSearching = NO;
    search.text = @"";
    search.showsCancelButton = NO;
    [self resetSearch];
    //[self setDDListHidden:YES];
    [table reloadData];
    [searchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
    search.showsCancelButton = YES;
    [table reloadData];
}



- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title
			   atIndex:(NSInteger)index {
    NSString *key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    else return index;
}

@end
